import axios,{AxiosRequestConfig,AxiosResponse} from 'axios';
const Authorization = localStorage.getItem('TOKEN') || null;
const apiBase = process.env.VUE_APP_API_BASE_URL || '';
const config = {
    baseURL:
        location.protocol === 'http:'
            ? apiBase.replace('https:', 'http:')
            : apiBase,
    timeout: 30 * 1000,
    headers: {
        'Content-Type': 'application/json',
        common: {
            Authorization
        }
    }
};

const _axios = axios.create(config);

export default app => {
    const GL = app.config.globalProperties;
    _axios.interceptors.request.use(
        (config:AxiosRequestConfig) => {
            if (config.params) {
                config.params.v = process.env.VUE_APP_API_V;
            } else {
                config.params = { v: process.env.VUE_APP_API_V };
            }
            if (config.method === 'get') {
                config.params = GL.$utils.dataFormat(config.params);
            } else if (config.data) {
                config.data = GL.$utils.dataFormat(config.data);
            }
            return config;
        },
        (error: any) => {
            console.log(error);
            return Promise.reject(error);
        }
    );

    _axios.interceptors.response.use(
        (res:AxiosResponse) => {
            if (res.data.code !== 0 && res.data.code !== 1) {
                if (res.data.code === 4001) {
                    GL.$router.replace({
                        name: 'Login'
                    });
                } else if (res.data.code === 4004) {
                    GL.$router.replace({
                        name: 'NoFind'
                    });
                }
                GL.$message.error(
                    res.data.msg || '服务器发生错误，请稍后再试。'
                );
                console.log(res);
                return Promise.reject(res);
            } else {
                // console.log('get', res.headers.authorization);
                if (res.headers.authorization) {
                    localStorage.setItem('TOKEN', res.headers.authorization);
                    GL.$axios.defaults.headers.common.Authorization =
                        res.headers.authorization;
                }
                // res.data.data = Utils.stringToNumber(res.data.data);
                res.data.data &&
                    (res.data.data = GL.$utils.dateFormat(res.data.data));
                return res.data;
            }
        },
        (error: any)=> {
            GL.$message.error('服务器发生错误，请稍后再试。');
            return Promise.reject(error);
        }
    );
    GL.$axios = _axios;
};
